
import dgram from "dgram"
import { netService } from "./net-service.ts"
import { electronLogger } from "../vendor/electron-logger.ts"
import { mainWindow } from "../windows/main-window.ts"


export default class UdpService {

  private broadCastSocket: dgram.Socket | null
  private broadCastTimer:  NodeJS.Timeout

  private clientSocket: dgram.Socket | null

  startBroadCast(id: string, port: number){
    if (this.broadCastSocket){
      this.stopBroadCast()
    }

    const netIf = netService.getNetIfById(id)
    this.broadCastSocket = dgram.createSocket("udp4");

    this.broadCastSocket.bind({address: netIf.ipv4}, () => {
      this.broadCastSocket!.setBroadcast(true);
    });

    this.broadCastTimer = setInterval(()=>{
      const broadData = `alin|${netIf.ipv4}`
      this.broadCastSocket!.send(broadData, 0, broadData.length, port, '255.255.255.255', (err, bytes)=>{
        electronLogger.info("发送广播", err, broadData, port)
      });
    }, 1000)
  }

  stopBroadCast(){
    clearInterval(this.broadCastTimer)
    if (!this.broadCastSocket) {
      return
    }
    this.broadCastSocket.close()
    this.broadCastSocket = null
  }

  beginClient(port: number){
    if (this.clientSocket != null){
      this.stopClient()
    }

    this.clientSocket = dgram.createSocket("udp4");
    this.clientSocket.bind(port);

    electronLogger.info("Starting Client", port);

    this.clientSocket.on("error", (err)=> {
      electronLogger.error("Client error:n" + err.stack);
      if (this.clientSocket) {
        this.stopClient()
      }
    });

    this.clientSocket.on("message", (msg, rinfo) =>{

      const data = msg.toString()
      electronLogger.info("Client Get msg", data, rinfo);
      if (data.length > 4 && data.substring(0, 4) == 'alin') {
        mainWindow.send("broadcast", data, rinfo);
      }
    });

    this.clientSocket.on("listening", function () {

    });
  }

  stopClient(){
    if (!this.clientSocket) {
      return
    }
    this.clientSocket.close();
    this.clientSocket = null
  }

}


export const udpService = new UdpService()
